package com.liu.community.schedule;/*
 *@Author:Liu Xing-zhi
 *Description:  定时器
 *Date:Crated in 10:26 2021/11/11
 */

import com.liu.community.cache.HotTagsCache;
import com.liu.community.mapper.QuestionMapper;
import com.liu.community.pojor.Question;
import com.liu.community.server.QuestionService;
import com.liu.community.utils.StringUtilByLike;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.*;

@Component
@Slf4j
public class HotTagsTasks {

    @Autowired
    private QuestionMapper questionMapper;
    @Autowired
    private  HotTagsCache hotTagsCache;

    @Scheduled(fixedRate = 1000*60*60*3)//1000毫秒*60*60*3  3小时更新一次//
    //@Scheduled(fixedRate = 10000)//1000毫秒*60*60*4  4小时更新一次
    //@Scheduled(cron = "0 0 1 * * *")//每天凌晨一点执行
    public void hotTagsSchedule() {
        int begin = 0;
        int limit = 5;
        log.info("The time is start {}", new Date());
        List<Question> questionList = new ArrayList<>();
        Map<String, Integer> tagMap = new HashMap<>();

        while (begin == 0 || questionList.size() == limit){
            String search = null;
            String inputTag = null;
            String searchLike = StringUtilByLike.getSearch(search);
            String tagLike = StringUtilByLike.getSearch(inputTag);

            questionList = questionMapper.queryAllQuestion(tagLike,searchLike, begin, limit);
            for (Question question : questionList) {
                String tag = question.getTag();
                String[] split = StringUtils.split(tag, ",");
                for (String s : split) {
                    Integer tagNum = tagMap.get(s);
                    if (tagNum != null){
                        tagMap.put(s,tagNum + 5 + question.getCommentCount());
                    }else {
                        tagMap.put(s, 5 + question.getCommentCount());
                    }
                }
//                log.info("this questionId is {}",question.getId());
            }

            begin += limit;
        }
       /* tagMap.forEach(
                (k,v)->{
                        System.out.print(k);
                        System.out.print(":");
                        System.out.print(v);
                        System.out.println();
           });*/
        hotTagsCache.updateTags(tagMap);
        log.info("The time is stop {}", new Date());

    }
}
